package com.lnb.service.impl;

import com.lnb.entity.Modules;
import com.lnb.mapper.ModulesMapper;
import com.lnb.service.IModulesService;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author liningbo
 * @since 2020-05-21
 */
@Service
public class ModulesServiceImpl extends ServiceImpl<ModulesMapper, Modules> implements IModulesService {

	@Autowired
	ModulesMapper modulesMapper;
	
	//需要设置为true的模块id集合
	List <Integer> modulIds =null;
	
	
	// 查询模块树形数据
	  @Override
	  public List<Modules> getModulesTree() {
		  modulIds =null;
	    // 获取所有的模块（平查）
	    List<Modules> list = this.baseMapper.selectList(null);
	    // 声明一个集合用来保存结果
	    List<Modules> tree = new ArrayList<>();
	    // 遍历集合，判断模块的父节点是否为0，若是，则此模块是根节点
	    for (Modules m : list) {
	      if (m.getParentId() != null && m.getParentId() == 0) {
	        tree.add(findChildren(m, list));
	      }
	    }
	    return tree;
	  }

	  /**
	   * 1递归查询子模块
	   * 
	   * @param m
	   * @param list
	   * @return
	   */
	  public Modules findChildren(Modules m, List<Modules> list) {
	    for (Modules item : list) {
	    	if(modulIds!=null && modulIds.contains(item.getId())) {
	    		item.setChecked(true);
	    	}
	      if (m.getId() == item.getParentId()) {
	        if (m.getChildren() == null) {
	          m.setChildren(new ArrayList<Modules>());
	        }
	        m.getChildren().add(findChildren(item, list));
	      }
	    }
	    return m;
	  }
	  
	  

		
	

	@Override
	public List<Modules> getModulesTreeByRoleId(Integer rid) {
		//获取指定用户角色拥有的模块id
		  modulIds=modulesMapper.getModulesTreeByRoleId(rid);
		
		//获取所有的模块(平查)
		 List<Modules> list = this.baseMapper.selectList(null);
		    // 声明一个集合用来保存结果
		    List<Modules> tree = new ArrayList<>();
		    // 遍历集合，判断模块的父节点是否为0，若是，则此模块是根节点
		    for (Modules m : list) {
		      if (m.getParentId() != null && m.getParentId() == 0) {
		        tree.add(findChildren(m, list));
		      }
		    }
		    return tree;
	}


	
	
	
	
	
	
	
	
	
	
	
	@Override
	public List<Modules> getModulesTreeByUserId(Integer uid) {
		 modulIds =null;
		   List<Modules> list = modulesMapper.getModulesListByUserId(uid);
		// 声明一个集合用来保存结果
		   List<Modules> tree = new ArrayList<>();
	    // 遍历集合，判断模块的父节点是否为0，若是，则此模块是根节点
	    for (Modules m : list) {
	      if (m.getParentId() != null && m.getParentId() == 0) {
	        tree.add(findChildren(m, list));
	      }
	    }
	    return tree;
	}









}
